package com.huiying.service.Impl;

import com.huiying.constant.MessageConstant;
import com.huiying.properties.VerifyCodeProperties;
import com.huiying.service.VerifyCodeService;
import com.huiying.utils.CodeUtils;
import com.huiying.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author: lsh
 * @Date: 2024/10/27/14:50
 * @Description:
 */
@Service
public class VerifyCodeServiceImpl implements VerifyCodeService {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private VerifyCodeProperties verifyCodeProperties;
    /***
     *  获取验证码
     * @return: java.util.Map<java.lang.String,java.lang.String>
     */
    @Override
    public Map<String, Object> getVerifyCode() {
        Map<String,Object> map = new HashMap<>();
        Object[] objects = CodeUtils.createImage();
        //验证码字符串和图片BufferedImage对象
        //获取验证码字符串，全部转为小写
        String codeStr = objects[0].toString().toLowerCase();
        //获取图片BufferedImage对象
        BufferedImage codeImg = (BufferedImage) objects[1];
        //图片Key对象
        String codeKey = System.currentTimeMillis() + "";
        //构造缓存Key
        String cacheKey = verifyCodeProperties.getPrefix() + codeKey;
        //将数据存入缓存
        redisCache.setCacheObject(cacheKey,codeStr, verifyCodeProperties.getTimeout(), TimeUnit.SECONDS);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try{
            ImageIO.write(codeImg, verifyCodeProperties.getType(), baos);
        }catch (Exception e){
            throw new RuntimeException(MessageConstant.CODE_ACQUISITION_FAILED);
        }
        String codePic = new String(Base64.getEncoder().encode(baos.toByteArray()));
        map.put("codeKey",codeKey);
        map.put("codePic",codePic);
        return map;
    }

    /***
     * verifyCodeService.checkCode(codeKey, inputCode)
     * @param codeKey 验证码图片
     * @param inputCode 用户输入的验证码
     * @return: java.lang.Boolean
     */
    @Override
    public Boolean checkCode(String codeKey, String inputCode) {
        //构造缓存Key
        String cacheKey = verifyCodeProperties.getPrefix() + codeKey;
        //获取缓存Value
        String cacheValue = redisCache.getCacheObject(cacheKey);
        return Objects.nonNull(cacheValue) && cacheValue.equalsIgnoreCase(inputCode);
    }
}
